<template>
  <div class="table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="(tab.key || tab.key === 0) && tab.key !== 100">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <template v-if="searchVal.status != 100">
      <div class="search-w table-filter-form">
        <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getTableList">
          <template #tableBody>
            <a-table class="table-singe-line show-border-table" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ x: 1600, y: '100%' }">
              <template #columns>
                <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                  <template v-if="item.tip" #title>
                    <a-popover>
                      <template #content>
                        <p style="max-width: 400px">{{ item.tip }}</p>
                      </template>
                      <p>
                        <span>{{ item.title }}</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>
                  <template v-if="item.dataIndex == 'sort'" #cell="{ rowIndex }">
                    <p>{{ rowIndex + 1 }}</p>
                  </template>
                  <template v-else-if="item.dataIndex == 'purchaseNo'" #cell="{ record }">
                    <div class="order-w flex-c-sb" style="padding-right: 20px">
                      <div class="flex">
                        <div class="order-detail-item flex-c" style="width: 200px">
                          <span class="label">交货单号：</span>
                          <span class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                        <div class="order-detail-item flex-c" style="width: 190px">
                          <span class="label">收货仓库：</span>
                          <TextLimit style="flex: 1" :val="`${record.warehouseName}(${record.warehouseCode})`" :rows="1" />
                        </div>
                        <div class="order-detail-item flex-c" style="width: 190px">
                          <span class="label">供应商：</span>
                          <TextLimit style="flex: 1" :val="`${record.supplierName}(${record.supplierCode})`" :rows="1" />
                        </div>
                        <div class="order-detail-item" style="width: 120px">
                          <p><span class="label">创建人：</span>{{ record.createUname }}</p>
                        </div>
                        <div class="order-detail-item" style="width: 190px">
                          <p><span class="label">创建时间：</span>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                        </div>
                        <div class="order-detail-item" style="width: 190px" v-if="record.status == 10">
                          <p><span class="label">提交时间：</span>{{ $setTime(record.gmtSubmit, 'YYYY/MM/DD HH:mm') }}</p>
                        </div>
                        <div class="order-detail-item" style="width: 190px" v-if="record.status == 30">
                          <p><span class="label">签收时间：</span>{{ $setTime(record.gmtFinished, 'YYYY/MM/DD HH:mm') }}</p>
                        </div>
                        <div class="order-detail-item" style="width: 190px" v-if="record.status == 20">
                          <p><span class="label">拒收时间：</span>{{ $setTime(record.gmtRefuse, 'YYYY/MM/DD HH:mm') }}</p>
                        </div>
                        <div class="order-detail-item flex-c warningColor" style="width: 200px; line-height: 1" v-if="record.status == 20">
                          <div class="flex-c">
                            <icon-exclamation-circle :size="14" />
                            <span>驳回原因：</span>
                          </div>
                          <TextLimit style="flex: 1; line-height: 1" class="warningColor" :val="record.refuseMsg" :rows="1" />
                        </div>
                      </div>
                      <div class="flex-c">
                        <a-space>
                          <a-tag color="arcoblue" size="small" bordered>{{ statusMap[record.status] }}</a-tag>
                          <div style="width: 60px; text-align: right">
                            <a-button type="text" @click="openSignDialog(record)" size="mini" v-if="[10].includes(record.status) && $authPass('procurement.delivery.sign')">签收</a-button>
                            <a-button type="text" @click="toDetail(record)" size="mini" v-else>详情</a-button>
                          </div>
                          <a-dropdown>
                            <icon-more class="table-btn-more" />
                            <template #content>
                              <a-doption @click.stop="toDetail(record)" v-if="[10].includes(record.status)">详情</a-doption>
                              <a-doption @click.stop="submitAgain([record.id])" v-if="[20].includes(record.status) && $authPass('procurement.delivery.submit')">再次提交</a-doption>
                              <a-doption @click.stop="openEdit(record)" v-if="[20].includes(record.status) && $authPass('procurement.delivery.update')">编辑</a-doption>
                              <a-doption @click.stop="submitCancellation([record.id])" v-if="[20].includes(record.status) && $authPass('procurement.delivery.cancel')">删除</a-doption>
                              <a-doption @click.stop="toPrintPDF([record.id])" v-if="[10, 30].includes(record.status) && $authPass('procurement.delivery.print')">打印</a-doption>
                              <a-doption @click.stop="openLogList(record)">日志</a-doption>
                            </template>
                          </a-dropdown>
                        </a-space>
                      </div>
                    </div>
                  </template>
                </a-table-column>
              </template>
              <template #expand-row="{ record }">
                <a-table class="table-singe-line" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
                  <template #columns>
                    <a-table-column :width="10" />
                    <a-table-column :width="40" />
                    <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                      <template v-if="item.dataIndex == 'sort'" #cell> </template>
                      <template v-else-if="item.dataIndex == 'img'" #cell="option">
                        <ImgPopover :src="option.record.productImg">
                          <template #con>
                            <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                          </template>
                        </ImgPopover>
                      </template>
                      <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                        <TextLimit :val="option.record.productName" :rows="1" />
                      </template>
                      <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                        <p class="highlight cursor">{{ option.record.sku }}</p>
                        <div class="urgent" v-show="option.record.urgent">急</div>
                      </template>
                      <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                        <TextLimit :val="getProductSpecs(option.record)" />
                      </template>
                      <template v-else-if="item.dataIndex == 'remark'" #cell="option">
                        <TextLimit :val="option.record.remark || '--'" :rows="2" />
                      </template>
                      <template v-else-if="item.dataIndex == 'gmtExpectDelivery'" #cell="option">
                        <p>{{ $setTime(option.record.gmtExpectDelivery, 'YYYY/MM/DD') }}</p>
                      </template>
                      <template v-else-if="['materialPrice', 'productPrice', 'laborPrice'].includes(item.dataIndex)" #cell="option">
                        <p>￥{{ option.record[item.dataIndex] }}</p>
                      </template>
                      <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                        <p>{{ option.record.rate }}%</p>
                        <p class="highlight">{{ option.record.priceType == 1 ? '含税' : '不含税' }}</p>
                      </template>
                      <template v-else-if="item.dataIndex == 'planNo'" #cell="option">
                        <p class="highlight">{{ option.record.planNo }}</p>
                      </template>
                    </a-table-column>
                  </template>
                </a-table>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </template>
    <template v-else>
      <div class="table-gl-con img-w">
        <a-image width="100%" style="max-width: 1000px" fit="contain" :preview="false" src="https://cdn2.selleroa.com/saas/product/165779903102091265.png" />
      </div>
    </template>
  </div>
  <!-- 签收 -->
  <PurchaseDeliverySign v-if="showSignDialog" :isShow="showSignDialog" :currentId="currentData.id" @closed="showSignDialog = false" @success="getListAndCount" />
  <!-- 编辑 -->
  <EditDeliveryOrderByPur v-if="showEditDialog" :isShow="showEditDialog" :currentItem="currentData" @closed="showEditDialog = false" @success="getListAndCount" />
  <!-- 日志列表 -->
  <CommonLogsDialog v-if="showLogDialog" api="findDeliveryLogPageV2" :id="currentData.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
  <!-- 发货单详情 -->
  <PurchaseDeliveryDetail v-if="showDetail" :isShow="showDetail" source="purchaser" :currentId="currentData.id" @closed="showDetail = false" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import EditDeliveryOrderByPur from '../components/editDeliveryOrderByPur.vue'
  import PurchaseDeliverySign from '../components/purchaseDeliverySign.vue'
  import PurchaseDeliveryDetail from '../components/purchaseDeliveryDetail.vue'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { findDeliveryPage, findDeliveryCountStatus, resubmitPurchaseDelivery, cancelPurchaseDelivery } from '@/api/purchaseApplication'
  import { findSupperList } from '@/api/system'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'
  import { useRouter } from 'vue-router'

  onMounted(async () => {
    getWareHouseList()
    getSupplierList()
    getListAndCount()
  })
  const tableColumns: Array<any> = [
    {
      title: '序号',
      dataIndex: 'sort',
      width: 40,
    },
    {
      title: '采购单',
      dataIndex: 'purchaseNo',
      width: 120,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 100,
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: 'SKU规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '采购员',
      dataIndex: 'purchaseUname',
      width: 70,
    },
    {
      title: '需求人',
      dataIndex: 'salesmanName',
      width: 70,
    },
    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      width: 100,
    },
    {
      title: '产品单价',
      dataIndex: 'productPrice',
      width: 70,
    },
    {
      title: '工费单价',
      dataIndex: 'laborPrice',
      width: 70,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 60,
    },
    {
      title: '交货数量',
      dataIndex: 'deliveryAmt',
      tip: '创建交货单时填写的数量',
      width: 85,
    },
    {
      title: '交货材质重量',
      dataIndex: 'materialWeight',
      tip: '金银等贵金属首饰类产品是按材质重量计算价格的，所以交货时必须要有材质重量',
      width: 110,
    },
    {
      title: '实际签收数量',
      dataIndex: 'deliveryRealAmt',
      tip: '交货单签收的实际数量',
      width: 100,
    },
    {
      title: '实收材质重量',
      dataIndex: 'materialRealWeight',
      tip: '实收材质重量=(交货材质重量/交货数量)*实际签收数量',
      width: 100,
    },
    {
      title: '材质金额',
      dataIndex: 'materialAmount',
      tip: '材质金额：--签收前=材质单价*交货材质重量--签收后=材质单价*实收材质重量',
      width: 85,
    },
    {
      title: '产品金额',
      dataIndex: 'productAmount',
      tip: '产品金额：--签收前=产品单价*交货数量--签收后=产品单价*实际签收数量',
      width: 85,
    },
    {
      title: '工费',
      dataIndex: 'laborAmount',
      tip: '工费金额：--签收前=工费单价*交货数量--签收后=工费单价*实际签收数量',
      width: 85,
    },
    {
      title: '其他费用',
      dataIndex: 'otherAmount',
      tip: '本次交货产生其他费用',
      width: 85,
    },
    {
      title: '合计金额',
      dataIndex: 'totalAmount',
      tip: '合计金额=材质金额+产品金额+工费+其他费用',
      width: 85,
    },
    {
      title: '税金',
      dataIndex: 'taxAmount',
      tip: '税金=税率*合计金额',
      width: 85,
    },
    {
      title: '单件货值',
      dataIndex: 'singleAmount',
      tip: '单件货值(含税)=（合计金额-税金）/实际签收数量--单件货值(不含税)=合计金额/实际签收数量',
      width: 85,
    },
  ]
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const tabsList = [
    { key: '', title: '全部' },
    { key: 10, title: '待签收' },
    { key: 20, title: '已拒收' },
    { key: 30, title: '已签收' },
    { key: 100, title: '采购交货流程' },
  ]
  const statusMap = {
    0: '已作废',
    1: '待出库',
    10: '待签收',
    20: '已拒收',
    30: '已签收',
  }
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [
        { label: '交货单号', value: 'billNos' },
        { label: '采购单号', value: 'purchaseNos' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: 'SKU', value: 'skus' },
        { label: '产品名称', value: 'productName' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'outWarehouseCode',
      label: '交货仓库',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'supplierId',
      label: '供应商',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },

    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '提交时间', value: 'gmtSubmit' },
        { label: '签收时间', value: 'gmtFinished' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: '',
  })
  const showDetail = ref(false)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const currentData = ref<any>({})
  const showSignDialog = ref(false)
  const showLogDialog = ref(false)
  const showEditDialog = ref(false)
  const countMap = ref<any>({})
  const supplierList = ref<Array<any>>([])
  const filterData = ref<any>({})
  const tableListref = ref()
  const useBaseData = useBaseDataStore()
  const router = useRouter()

  // 获取仓库列表
  async function getWareHouseList() {
    await useBaseData.getWareHouseList()
    filterItem.value[2].optionItems = useBaseData.warehouseList.map((el: any) => {
      return {
        label: el.warehouseName,
        value: el.warehouseCode,
      }
    })
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }

  //供应商列表
  async function getSupplierList() {
    const res: any = await findSupperList()
    supplierList.value = res?.data || []
    filterItem.value[3].optionItems = res?.data?.map((el: any) => {
      return {
        label: el.supplierName,
        value: el.id,
      }
    })
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    if (status === 100) return
    searchVal.value.pageNum = 1
    nextTick(() => {
      getTableList()
    })
  }
  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findDeliveryCountStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    tableList.value = []
    tableListref.value.selectAll(false)
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findDeliveryPage(params)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    expandable.value.expandedRowKeys = tableList.value.map((el: any) => el.id)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'purchaseNo') {
      return { rowspan: 1, colspan: 22 }
    }
  }
  // 再次提交
  function submitAgain(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择交货单')
      return
    }
    Modal.confirm({
      title: '提交交货单',
      content: `请确认是否再次提交交货单？`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await resubmitPurchaseDelivery({ ids: ids })
        if (res) {
          Message.success('提交审核成功')
          getListAndCount()
        }
      },
    })
  }
  // 删除
  function submitCancellation(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择交货单')
      return
    }
    Modal.confirm({
      title: '删除交货单',
      content: `请再次确认是否删除该交货单？`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await cancelPurchaseDelivery({ ids: ids })
        if (res) {
          Message.success('删除成功')
          getListAndCount()
        }
      },
    })
  }
  // 打开签收弹窗
  function openSignDialog(row: any) {
    currentData.value = row
    showSignDialog.value = true
  }
  // 打开编辑
  function openEdit(row: any) {
    currentData.value = row
    showEditDialog.value = true
  }

  // 打开日志列表
  function openLogList(row: any) {
    currentData.value = row
    showLogDialog.value = true
  }

  // 查看采购订单详情
  function toDetail(item: any) {
    currentData.value = item || {}
    showDetail.value = true
  }
  // 去打印
  function toPrintPDF(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择交货单')
      return
    }
    window.sessionStorage.setItem('purchaseDeliveryIdByPur', ids.join(','))
    router.push('/purchaseApplication/purchaser/purchaseDeliveryPrintPDFByPur')
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
    height: auto;
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
        height: 48px;
      }
    }
    background-color: #fff !important;
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    width: calc(100vw - @menuWidth - 130px);
    .order-detail-item {
      width: 200px;
      padding-right: 5px;
    }
  }
  .urgent {
    font-size: 12px;
    display: inline-block;
    background-color: red;
    color: #fff;
    width: 18px;
    border-radius: 50%;
    line-height: 18px;
    text-align: center;
    transform: scale(0.82);
  }
  .main-layout-close-status {
    .order-w {
      width: calc(100vw - @minMenuWidth - 130px);
    }
  }
  .img-w {
    padding: 10px 20px;
    overflow-y: auto;
  }
</style>
